import { observable, computed, action, toJS } from "mobx";
import { isEqual } from 'lodash';
import { listDataSetTableFields } from "../../apis/dataset";
import CellType from './celltypes';
import { WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

export default class FieldPropsStore {
    @observable tabs = [{
        key: '0',
        title: getLabel('506118','单元格'),
        icon: 'icon-coms-classification'
    }, {
        key: '1',
        title: getLabel('506120','表单设置'),
        icon: 'icon-coms-Flow-setting'
    }, {
        key: '2',
        title: getLabel('506121','显示设置'),
        icon: 'icon-coms-pic',
        disabled: true
    }];
    @observable selectedTabKey = '0';

    @observable dataSetList = [];
    @observable dataSetMap = {};
    @observable range;
    @observable table;

    @observable visible = true;
    @observable rowControl={};
    @observable cellTypeId = "";

    @computed get selectedIndex() {
        let index = 0;
        this.tabs.forEach((t, i) => {
            if (t.key === this.selectedTabKey) {
                index = i;
            }
        });
        return index;
    }
    @computed get tabsLength() {
        return this.tabs.length;
    }

    @computed get content() {
        return this.range && this.range.value();
    }
    cellType() {
        return this.range && (this.table ? this.range.sheet.getCell(this.table.dataRange().row, this.range.col).cellType() : this.range.cellType());
    }
    @computed get label() {
        const cellType = this.cellType();
        return cellType && cellType.label;
    }
    @computed get fieldType() {
        const cellType = this.cellType();
        return cellType && cellType.fieldType;
    }
    @computed get htmlType() {
        return this.fieldType && this.fieldType[0];
    }
    @computed get type() {
        return this.fieldType && this.fieldType[1];
    }
    @computed get isField() {
        const cellType = this.cellType();
        return !!(cellType && cellType.fieldType);
    }
    @computed get options() {
        const cellType = this.cellType();
        return cellType && cellType[2] && cellType[2].datas;
    }
    @computed get dbType() {
        return this.fieldType && this.fieldType[2];
    }
    @computed get tableOptions() {
        const list = this.dataSetMap[this.dataSet] || [];
        return list.map(({ key, showname }) => ({ key, showname }));
    }
    @computed get tableFieldOptions() {
        const list = this.dataSetMap[this.dataSet] || [];
        const tableArray = list.filter(d => d.key != "" && d.key === this.dsTable);
        let fieldOptions = [];
        if (tableArray.length > 0) {
            if(tableArray[0].children){
                fieldOptions = tableArray[0].children.map(d => ({ key: d.key, showname: d.showname }));
            }
        }
        fieldOptions.unshift({key:"",showname:""});
        return fieldOptions;
    }
    @computed get dataSet() {
        const cellType = this.cellType();
        return cellType && cellType.ds;
    }
    set dataSet(ds) {
        this.updateSheet(() => {
            let cellType = this.cellType();
            if (cellType) {
                cellType.ds = ds;
                this.cellTypeId = cellType.id; 
            } else {
                const NoFieldCellType = CellType('NoFieldCellType');
                cellType = new NoFieldCellType();
                cellType.ds = ds;
                this.range.cellType(cellType);
            }
            cellType.dsName = (this.dataSetList.filter(d => d.key === ds)[0] || {}).showname;
            this.parent().reEnterCell();
        })

    }
    @computed get dsTable() {
        const cellType = this.cellType();
        return cellType && cellType.table;
    }
    set dsTable({ table, tableName }) {
        this.updateSheet(() => {
            let cellType = this.cellType();
            if (cellType) {
                cellType.table = table;
                cellType.tableName = tableName;
                this.cellTypeId = cellType.id; 
            } else {
                const NoFieldCellType = CellType('NoFieldCellType');
                cellType = new NoFieldCellType();
                cellType.table = table;
                cellType.tableName = tableName;
                this.range.cellType(cellType);
            }
            this.parent().reEnterCell();
        })
    }
    @computed get dsField() {
        const cellType = this.cellType();
        return cellType && cellType.field;
    }
    set dsField(field) {
        this.updateSheet(() => {
            let cellType = this.cellType();
            if (cellType) {
                cellType.field = field;
                this.cellTypeId = cellType.id; 
            } else {
                const NoFieldCellType = CellType('NoFieldCellType');
                cellType = new NoFieldCellType();
                cellType.field = field;
                this.range.cellType(cellType);
            }
            this.parent().reEnterCell();
        })
    }

    @action toggle = () => {
        this.visible = !this.visible;
    }
    @action setdataSetList = (dataSetList) => {
        if (!isEqual(toJS(this.dataSetList), toJS(dataSetList))) {
            this.init(dataSetList);
        }
        this.dataSetList = dataSetList;
    }
    @action init = (list) => {
        Promise.all(list.map(ds => {
            if (ds.key != "") {
                return listDataSetTableFields(ds.key);
            }
        })).then(result => {
            const dataSetMap = {};
            list.forEach((ds, index) => {
                if(ds.key){
                    dataSetMap[ds.key] = [{ key: "", showname: "" }].concat(result[index]);
                }
            });
            this.dataSetMap = dataSetMap;
        });
    }
    @action initProps = (dataSetList, range, table, rowControl) => {
        dataSetList = dataSetList.map(d => ({ key: d.uuid, showname: d.name }));
        dataSetList.unshift({ key: "", showname: "" });
        this.setdataSetList(dataSetList);
        this.range = range;
        this.table = table;
        this.rowControl = rowControl;
        if (this.isField) {
            if(this.cellType().id !== this.cellTypeId) {
                this.selectedTabKey = '1';
            } 
        } else {
            this.selectedTabKey = '0';
        }
    }
    @action changeFieldLabel = (label) => {
        if (this.range) {
            this.range.sheet.suspendPaint();
            const cellType = this.cellType();
            if (cellType) {
                cellType.label = label;
                if (this.table) {
                    const index = this.range.col - this.table.dataRange().col;
                    this.table.setColumnName(index, label);
                }
            }
            this.range.sheet.resumePaint();
        }

    }
    @action changeDataSet = (ds) => {
        this.dataSet = ds;
        this.dsTable = {};
        this.dsField = "";
    }
    @action changeDataSetTable = (table) => {
        const tableName = (this.tableOptions.filter(d => d.key === table)[0] || {}).showname || '';
        this.dsTable = { table, tableName };
        this.dsField = "";
    }
    @action changeDataSetField = (field) => {
        this.dsField = field;
    }

    updateSheet = (func) => {
        this.range.sheet.suspendPaint();
        func();
        this.range.sheet.resumePaint()
    }

    @computed get isAddRow() {
        let result = 1;
        if (this.table) {
            const bindingPath = this.table.bindingPath();
            if(!bindingPath) {
                return;
            }
            const paths = bindingPath.split('.');
            const sheetName = paths[0];
            if(this.rowControl && this.rowControl[sheetName]){
                this.rowControl[sheetName].forEach(item => {
                    if(bindingPath == item.bindingPath){
                        result = item.isAddRow;
                        return;
                    }
                });
            }
        }  
        return result;
    }

    @computed get isDeleteRow() {
        let result = 1;
        if (this.table) {
            const bindingPath = this.table.bindingPath();
            if(!bindingPath) {
                return;
            }
            const paths = bindingPath.split('.');
            const sheetName = paths[0];
            if(this.rowControl && this.rowControl[sheetName])
            this.rowControl[sheetName].forEach(item => {
                if(bindingPath == item.bindingPath){
                    result = item.isDeleteRow;
                    return;
                }
            });
        }  
        return result;
    }

    @action changeRowControl = (type, isRowControl) => {
        if (this.table) {
            const bindingPath = this.table.bindingPath();
            if(!bindingPath) {
                return;
            }
            const paths = bindingPath.split('.');
            const sheetName = paths[0];
            const rowControl  = this.rowControl;
            if(rowControl){
                if(rowControl[sheetName]){
                    var arr= rowControl[sheetName].filter(function(item){
                        return item.bindingPath == bindingPath; 
                    })
                    if(arr.length==0){
                        if('add' == type){
                            let tableControl= {bindingPath: bindingPath ,isAddRow: isRowControl,isDeleteRow: 1};
                            rowControl[sheetName].push(tableControl);
                        } else if('delete' == type){
                            let tableControl= {bindingPath: bindingPath ,isAddRow: 1, isDeleteRow: isRowControl};
                            rowControl[sheetName].push(tableControl);
                        }
                    } else {
                        rowControl[sheetName].forEach(item => {
                            if(bindingPath == item.bindingPath){
                                if('add' == type){
                                    item.isAddRow = isRowControl;
                                } else if('delete' == type){
                                    item.isDeleteRow = isRowControl;
                                }
                                return;
                            }
                        });
                    }
                } else {
                    let sheetControl = new Array();　
                    if('add' == type){
                        let tableControl= {bindingPath: bindingPath ,isAddRow: isRowControl,isDeleteRow: 1};
                        sheetControl.push(tableControl);
                    } else if('delete' == type){
                        let tableControl= {bindingPath: bindingPath ,isAddRow: 1, isDeleteRow: isRowControl};
                        sheetControl.push(tableControl);
                    }
                    rowControl[sheetName] = sheetControl;
                }
            } else {
                let sheetControl = new Array();　
                if('add' == type){
                    let tableControl= {bindingPath: bindingPath ,isAddRow: isRowControl,isDeleteRow: 1};
                    sheetControl.push(tableControl);
                } else if('delete' == type){
                    let tableControl= {bindingPath: bindingPath ,isAddRow: 1, isDeleteRow: isRowControl};
                    sheetControl.push(tableControl);
                }
                rowControl[sheetName] = sheetControl;
            }
        }
    }
}